package Recorder;



import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Vector;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import javax.media.MediaLocator;

import SA.Gms.Ui.Util.ReadTestCase;
import SA.Gms.Ui.Util.ReadTestSuite;


/**
 * @author Sadaiyandi
 *
 */
public class Recorder {

	/**
	 * Screen Width.
	 */
	public static int screenWidth = (int) Toolkit.getDefaultToolkit()
			.getScreenSize().getWidth();

	/**
	 * Screen Height.
	 */
	public static int screenHeight = (int) Toolkit.getDefaultToolkit()
			.getScreenSize().getHeight();

	/**
	 * Interval between which the image needs to be captured.
	 */
	public static int captureInterval = 50;

	/**
	 * Temporary folder to store the screenshot.
	 */
	public static String store = "tmp";

	/**
	 * Status of the recorder.
	 */
	public static boolean record = false;
	public static boolean status = false;
	
	public static void Screencapture(String tcname) {
		Robot rt1 = null;
		try {
			rt1 = new Robot();
		} catch (AWTException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		BufferedImage img = rt1.createScreenCapture(new Rectangle((int) Toolkit.getDefaultToolkit()
						.getScreenSize().getWidth(),(int) Toolkit.getDefaultToolkit()
						.getScreenSize().getHeight()));
		try {
			ImageIO.write(img, "jpeg", new File(ReadTestSuite.OutPath+File.separator+ReadTestCase.TcName+"/"+tcname+System.currentTimeMillis() + ".jpeg"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	
	
	

	/**
	 * 
	 */
	public static void startRecordOrginal() {
		Thread recordThread = new Thread() {
			@Override
			public void run() {
				Robot rt;
				int cnt = 0;
				try {
					rt = new Robot();
					while (cnt == 0 || record) {
						BufferedImage img = rt
								.createScreenCapture(new Rectangle(screenWidth,
										screenHeight));
						ImageIO.write(img, "jpeg", new File("./"+store+"/"
								+ System.currentTimeMillis() + ".jpeg"));
						if (cnt == 0) {
							record = true;
							cnt = 1;
						}
						// System.out.println(record);
						Thread.sleep(captureInterval/2);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		recordThread.start();
	}

	//my custom to reduce size
	public static void startRecord() {
		Thread recordThread = new Thread() {
			@Override
			public void run() {
				Robot rt;
				int cnt = 0;
				try {
					rt = new Robot();
					while (cnt == 0 || record) {
						BufferedImage img = rt
								.createScreenCapture(new Rectangle(screenWidth,
										screenHeight));
						Iterator<ImageWriter> i = ImageIO.getImageWritersByFormatName("jpeg");
						ImageWriter jpegWriter = i.next();
						// Set the compression quality to 0.8
						ImageWriteParam param = jpegWriter.getDefaultWriteParam();
						param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
						param.setCompressionQuality(0.4f);
						// Write the image to a file
						FileImageOutputStream out = new FileImageOutputStream(new File("./"+store+"/"
								+ System.currentTimeMillis() + ".jpeg"));
						jpegWriter.setOutput(out);
						jpegWriter.write(null, new IIOImage(img, null, null), param);
						jpegWriter.dispose();
						out.close();

						
						/*ImageIO.write(img, "jpeg", new File("./"+store+"/"
								+ System.currentTimeMillis() + ".jpeg"));*/
						if (cnt == 0) {
							record = true;
							cnt = 1;
						}
						// System.out.println(record);
						Thread.sleep(captureInterval/2);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		recordThread.start();
	}
	
	
	
	
	
	
	
	
	/**
	 * @throws MalformedURLException 
	 * 
	 */
	public static void makeVideo(String movFile) throws MalformedURLException {
		System.out
				.println("#### SA Screen Maker  Creating video, please wait!!! ####");
		JpegImagesToMovie imageToMovie = new JpegImagesToMovie();
		Vector<String> imgLst = new Vector<String>();
		File f = new File(store);
		File[] fileLst = f.listFiles();
		for (int i = 0; i < fileLst.length; i++) {
			imgLst.add(fileLst[i].getAbsolutePath());
		}
		// Generate the output media locators.
		MediaLocator oml;
		if ((oml = imageToMovie.createMediaLocator(movFile)) == null) {
			System.err.println("Cannot build media locator from: " + movFile);
			System.exit(0);
		}
		imageToMovie.doIt(screenWidth, screenHeight, (300 / captureInterval),
				imgLst, oml);

	}

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		System.out.println("######### Starting SA Screen Recorder  #######");
		Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
		System.out.println("Your Screen [Width,Height]:" + "["
				+ screen.getWidth() + "," + screen.getHeight() + "]");
		Scanner sc = new Scanner(System.in);
		System.out.println("Rate 20 Frames/Per Sec.");
		System.out
				.print("Do you wanna change the screen capture area (y/n) ? ");
		if (sc.next().equalsIgnoreCase("y")) {
			System.out.print("Enter the width:");
			screenWidth = sc.nextInt();
			System.out.print("Enter the Height:");
			screenHeight = sc.nextInt();
			System.out.println("Your Screen [Width,Height]:" + "["
					+ screen.getWidth() + "," + screen.getHeight() + "]");
		}
		System.out
				.print("Now move to the screen you want to record");
		for(int i=0;i<5;i++){
			System.out.print(".");
			Thread.sleep(1000);
		}
		File f = new File(store);
		if(!f.exists()){
			f.mkdir();
		}
		startRecord();
		System.out
		.println("\nSA Screen Recorder is recording now!!!!!!!");

		System.out.println("Press e to exit:");
		String exit = sc.next();
		while (exit == null || "".equals(exit) || !"e".equalsIgnoreCase(exit)) {
			System.out.println("\nPress e to exit:");
			exit = sc.next();
		}
		record = false;
		
		System.out.println("SA Screen Recorder has stopped.");
		makeVideo(System.currentTimeMillis()+".mov");
		clearstore();
		System.out.println("done");
		
	}
	
	public static void startRecording ()
	{
		status=true;
		System.out.println("######### Starting SA Screen Recorder  #######");
		Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
		System.out.println("Your Screen [Width,Height]:" + "["
				+ screen.getWidth() + "," + screen.getHeight() + "]");
		Scanner sc = new Scanner(System.in);
		System.out.println("Rate 20 Frames/Per Sec.");
		
		System.out
				.print("Now move to the screen you want to record");
		for(int i=0;i<5;i++){
			System.out.print(".");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		File f = new File(store);
		if(!f.exists()){
			f.mkdir();
		}
		startRecord();
		System.out
		.println("\nSA Screen Recorder is recording now!!!!!!!");

		
		
		
	
	}
	public static void stopRecording(String tcname)
	{
		if(record==true)
		{
			record = false;
			
			System.out.println("SA Screen Recorder has stopped.");
			try {
				makeVideo(tcname+System.currentTimeMillis()+".mov");
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				clearstore();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("done");
			status=false;	
		}
		
	}
	
	
	public static void clearstore()throws IOException
	{
		File directory = new File("./"+store+"/");
		 
		        //get all the files from a directory
		        File[] fList = directory.listFiles();
		        String a1 [] = null;
		        for (File file : fList){
		            if (file.isFile()){
		            	file.delete();
		            	
		            }
		        }
		        directory.delete(); 
	}
}
